﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using PomodoroSuite.EntidadesNegocio;
using PomodoroSuite.EntidadesNegocio.Enumeradores;
using PomodoroSuite.FrontEnd.Win.Properties;
using PomodoroSuite.FW.Comun.Apoyo;
using PomodoroSuite.FW.DAL;

namespace PomodoroSuite.FrontEnd.Win
{
    public partial class frmTodoHoy : KryptonForm
    {
        #region " Campos "

        private DalGenerico<Tarea> dalTarea = null;
        private List<TareaSet> colTareaSet = new List<TareaSet>();
        private frmControlPomodoro control = null;

        #endregion

        #region " Constructor "

        public frmTodoHoy()
        {
            InitializeComponent();
            dalTarea = FabricaDAL.ObtenerDal<Tarea>();
        }

        #endregion

        #region " Eventos "

        public event EventHandler OnRefrescar;

        #endregion

        #region " Eventos Formulario "

        private void frmTodoHoy_Load(object sender, EventArgs e)
        {
            List<Filtro> filtros = new List<Filtro>();
            filtros.Add(new Filtro("IdUsuario", Program.UsuarioActivo.IdUsuario));
            filtros.Add(new Filtro("FechaInicio", Operacion.MayorIgual, DateTime.Now.Date));
            filtros.Add(new Filtro("FechaInicio", Operacion.Menor, DateTime.Now.Date.AddDays(1)));
            filtros[2].NombreVariable = "FechaCreacionFin";
            gridTareas.DataSource = dalTarea.ObtenerListadoFiltrado(filtros);
            filtros.Clear();

            string inClause = string.Join(",",
                    (gridTareas.DataSource as IList<Tarea>)
                        .Where(x => x.IdTareaSet != null)
                        .Select(x => x.IdTareaSet.ToString()).ToArray());

            if (!string.IsNullOrEmpty(inClause))
            {
                Query query = new Query();
                query.Sentencia = "SELECT ts.* FROM TareaSet AS ts INNER JOIN Tarea AS t ON ts.IdTareaSet = t.IdTareaSet WHERE ts.IdTareaSet IN (" + inClause + ")";
                query.Tipo = CommandType.Text;

                colTareaSet = FabricaDAL.ObtenerDal<TareaSet>().EjecutarQuery(query);
            }
        }

        private void gridTareas_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            Tarea tarea = gridTareas.Rows[e.RowIndex].DataBoundItem as Tarea;
            CargarTarea(tarea);
            if (tarea.IdTareaSet.HasValue)
                CargarTareaSet(tarea.IdTareaSet.Value);
            else
            {
                lblPomodoroFechaFin.Text = "";
                lblPomodoroFechaInicio.Text = "";
                lblPomodoroNroPomodoros.Text = "";
            }
        }

        private void gridTareas_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            switch ((gridTareas.Rows[e.RowIndex].DataBoundItem as Tarea).EstadoTarea)
            {
                case Estado.Planeado:
                    break;
                case Estado.EnProgreso:
                    gridTareas.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
                    break;
                case Estado.Terminado:
                    gridTareas.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.YellowGreen;
                    break;
                case Estado.Cancelado:
                    gridTareas.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Crimson;
                    gridTareas.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White;
                    break;
            }
        }

        private void iniciarPomodoroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ((MdiParent as Shell).EnDescanso)
            {
                MessageBox.Show(Resources.frmToDoHoy_EnDescanso, Resources.comun_Informacion, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (gridTareas.SelectedRows != null && gridTareas.SelectedRows.Count > 0)
            {
                Tarea tarea = gridTareas.SelectedRows[0].DataBoundItem as Tarea;
                switch (tarea.EstadoTarea)
                {
                    case Estado.Planeado:
                    case Estado.EnProgreso:
                        if (control == null)
                        {
                            control = new frmControlPomodoro(tarea, colTareaSet.FirstOrDefault(x => x.IdTareaSet == tarea.IdTareaSet));
                            control.FormClosing += new FormClosingEventHandler(control_FormClosing);
                            control.FormClosed += new FormClosedEventHandler(control_FormClosed);
                            control.Show(this);
                            if (OnRefrescar != null)
                                OnRefrescar(null, e);
                        }
                        else
                        {
                            MessageBox.Show(Resources.frmToDoHoy_PomodoroIniciado, Resources.comun_Informacion, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        break;
                    case Estado.Terminado:
                    case Estado.Cancelado:
                        MessageBox.Show(Resources.frmToDoHoy_TareaTerminada, Resources.comun_Informacion, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                }
            }
        }

        private void terminarTareaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridTareas.SelectedRows != null && gridTareas.SelectedRows.Count > 0)
            {
                if (MessageBox.Show(Resources.frmToDoHoy_ConfirmarTerminar, Resources.comun_Informacion, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Tarea tarea = gridTareas.SelectedRows[0].DataBoundItem as Tarea;
                    if (tarea.EstadoTarea == Estado.EnProgreso)
                    {
                        tarea.EstadoTarea = Estado.Terminado;
                        dalTarea.Actualizar(tarea);
                        gridTareas.Refresh();
                        if (OnRefrescar != null)
                            OnRefrescar(null, e);
                    }
                }
            }
        }

        private void cancelarTareaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridTareas.SelectedRows != null && gridTareas.SelectedRows.Count > 0)
            {
                if (MessageBox.Show(Resources.frmToDoHoy_ConfirmarCancelar, Resources.comun_Informacion, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Tarea tarea = gridTareas.SelectedRows[0].DataBoundItem as Tarea;
                    if (tarea.EstadoTarea != Estado.Cancelado)
                    {
                        tarea.EstadoTarea = Estado.Cancelado;
                        dalTarea.Actualizar(tarea);
                        gridTareas.Refresh();
                        if (OnRefrescar != null)
                            OnRefrescar(null, e);
                    }
                }
            }
        }

        private void verPomodorosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridTareas.SelectedRows != null && gridTareas.SelectedRows.Count > 0)
            {
                Tarea tarea = gridTareas.SelectedRows[0].DataBoundItem as Tarea;
                if (tarea.IdTareaSet.HasValue)
                {
                    frmVisorPomodoros pomodoros = new frmVisorPomodoros(tarea.IdTareaSet.Value);
                    pomodoros.ShowDialog();
                }
            }
        }

        private void control_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (colTareaSet.FirstOrDefault(x => x.IdTareaSet == (sender as frmControlPomodoro).ObjTarea.IdTareaSet) == null)
            {
                colTareaSet.Add((sender as frmControlPomodoro).ObjTareaSet.Clone<TareaSet>());
            }
            gridTareas.Refresh();
        }

        private void control_FormClosed(object sender, FormClosedEventArgs e)
        {
            control.Dispose();
            control = null;
        }

        #endregion

        #region " Métodos "

        public void Refrescar(object sender, EventArgs e)
        {
            frmTodoHoy_Load(sender, e);
        }

        private void CargarTarea(Tarea tarea)
        {
            lblNombre.Text = tarea.Nombre;
            lblDescripcion.Text = tarea.Descripcion;
            lblTag.Text = tarea.Tag;
            lblInicio.Text = (tarea.FechaInicio.HasValue) ? tarea.FechaInicio.Value.Date.ToShortDateString() : Resources.comun_SinInicio;
            switch (tarea.PrioridadTarea)
            {
                case Prioridad.Baja:
                    lblPrioridad.Text = Resources.prioridad_Baja;
                    break;
                case Prioridad.Normal:
                    lblPrioridad.Text = Resources.prioridad_Normal;
                    break;
                case Prioridad.Alta:
                    lblPrioridad.Text = Resources.prioridad_Alta;
                    break;
            }
            switch (tarea.EstadoTarea)
            {
                case Estado.Planeado:
                    lblEstado.Text = Resources.estado_Planeado;
                    break;
                case Estado.EnProgreso:
                    lblEstado.Text = Resources.estado_EnProgreso;
                    break;
                case Estado.Terminado:
                    lblEstado.Text = Resources.estado_Terminado;
                    break;
                case Estado.Cancelado:
                    lblEstado.Text = Resources.estado_Cancelado;
                    break;
            }
            switch (tarea.PlanificacionTarea)
            {
                case Planificacion.Planeado:
                    lblPlanificacion.Text = Resources.planificacion_Planeado;
                    break;
                case Planificacion.NoPlaneado:
                    lblPlanificacion.Text = Resources.planificacion_NoPlaneado;
                    break;
            }
        }

        private void CargarTareaSet(int idTareaSet)
        {
            TareaSet set = colTareaSet.FirstOrDefault(x => x.IdTareaSet == idTareaSet);
            if (set != null)
            {
                lblPomodoroFechaInicio.Text = set.HoraInicio.ToString();
                lblPomodoroFechaFin.Text = (set.HoraFinalizacion.HasValue) ? set.HoraFinalizacion.Value.ToString() : "";
                lblPomodoroNroPomodoros.Text = set.NumeroPomodoros.ToString();
            }
        }

        #endregion
    }
}
